// src/main/java/swb/api/com/service/impl/SmsServiceImpl.java
package swb.api.com.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import swb.api.com.common.exception.SwbException;
import swb.api.com.repository.SmsVerificationCodeRepository;
import swb.api.com.repository.dto.SmsVerificationCode;
import swb.api.com.service.SmsService;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * 阿里云短信服务实现（使用数据库存储验证码）
 */
@Slf4j
@Service
@Transactional
public class SmsServiceImpl implements SmsService {

    // 阿里云短信配置
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    // 验证码有效期（分钟）
    @Value("${aliyun.sms.expireTime:5}")
    private int expireTime;

    // 发送次数限制时间范围（分钟）
    @Value("${aliyun.sms.sendLimitTime:5}")
    private int sendLimitTime;

    // 发送次数限制
    @Value("${aliyun.sms.sendLimitCount:3}")
    private int sendLimitCount;

    @Autowired
    private SmsVerificationCodeRepository smsVerificationCodeRepository;

    @Override
    @Transactional
    public boolean sendVerificationCode(String mobile) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime timeLimit = now.minusMinutes(sendLimitTime);

            // 检查发送次数限制
            SmsVerificationCode existingCode = smsVerificationCodeRepository
                    .findByMobileAndTimeRange(mobile, timeLimit)
                    .orElse(null);

            if (existingCode != null && existingCode.getSendCount() >= sendLimitCount) {
                log.warn("手机号 {} 在 {} 分钟内发送验证码次数超过限制 {}", mobile, sendLimitTime, sendLimitCount);
                throw new SwbException(sendLimitTime + "分钟内发送验证码次数不能超过" + sendLimitCount + "次");
            }

            // 生成6位随机验证码
            String code = String.format("%06d", new Random().nextInt(999999));

            // 更新或创建验证码记录
            SmsVerificationCode smsCode;
            if (existingCode != null) {
                smsCode = existingCode;
                smsCode.setCode(code);
                smsCode.setCreatedTime(now);
                smsCode.setExpireTime(now.plusMinutes(expireTime));
                smsCode.setSendCount(smsCode.getSendCount() + 1);
            } else {
                smsCode = new SmsVerificationCode();
                smsCode.setMobile(mobile);
                smsCode.setCode(code);
                smsCode.setCreatedTime(now);
                smsCode.setExpireTime(now.plusMinutes(expireTime));
                smsCode.setSendCount(1);
            }
            smsCode.setLastSendTime(now);

            smsVerificationCodeRepository.save(smsCode);

            // 调用阿里云短信服务发送验证码
            // 这里需要集成阿里云短信SDK
            // com.aliyun.dysmsapi20170525.Client client = createClient();
            // SendSmsRequest sendSmsRequest = new SendSmsRequest()
            //     .setPhoneNumbers(mobile)
            //     .setSignName(signName)
            //     .setTemplateCode(templateCode)
            //     .setTemplateParam("{\"code\":\"" + code + "\"}");
            // SendSmsResponse response = client.sendSms(sendSmsRequest);

            // 模拟发送成功
            log.info("发送短信验证码: {} 到手机号: {}", code, mobile);
            return true;
        } catch (SwbException e) {
            throw new SwbException(e.getMessage());
        } catch (Exception e) {
            log.error("发送短信验证码失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean verifyCode(String mobile, String code) {
        try {
            // 查找验证码
            SmsVerificationCode smsCode = smsVerificationCodeRepository.findByMobile(mobile)
                    .orElse(null);

            if (smsCode == null) {
                return false; // 验证码不存在
            }

            // 检查是否过期
            if (LocalDateTime.now().isAfter(smsCode.getExpireTime())) {
                // 删除过期验证码
                smsVerificationCodeRepository.deleteByMobile(mobile);
                return false; // 验证码已过期
            }

            boolean isValid = smsCode.getCode().equals(code);
            if (isValid) {
                // 验证成功后删除验证码
                smsVerificationCodeRepository.deleteByMobile(mobile);
            }

            return isValid;
        } catch (Exception e) {
            log.error("验证短信验证码失败", e);
            return false;
        }
    }
}
